package com.qk.management.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.vo.homePage.HomePageVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/*
 *  @author SHCJ
 *  @created 2025/10/17 11:39
 *  @description
 */
@Slf4j
@Aspect
@Component
public class HomePageRedisAspect {
    //        创建redis对象
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final String CACHE_PORTAL_KEY_PREFIX = "qk:portal:";
    @Pointcut("execution(* com.qk.management.service.impl.HomePageServiceImpl.homePage())")
    public void pointcut() {}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("AOP实现redis缓存数据成功");
        String redisKey = CACHE_PORTAL_KEY_PREFIX + "homePage";
        String json = stringRedisTemplate.opsForValue().get(redisKey);
        try {
            if(ObjectUtil.isNotEmpty( json)){
                return JSONUtil.toBean(json, HomePageVO.class);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Object proceed = joinPoint.proceed();
        try {
//        查询完把数据存到redis中
            stringRedisTemplate.opsForValue().set(redisKey, JSONUtil.toJsonStr(proceed));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return proceed;
    }
}
